<?php

declare(strict_types=1);

namespace Modules\User\Support;

use Catch\Facade\Admin;
use Modules\User\Events\AdminBehaviorEvent;
use Modules\User\Models\User;
use Pro\Support\Helper;

/**
 * 管理员行为日志助手类
 */
class AdminBehaviorLogger
{
    /**
     * 记录管理员行为日志
     *
     * @param string $action 操作行为
     * @param array $content 操作内容
     * @param string|null $ip IP地址（可选）
     * @param int|null $creatorId 操作者ID（可选）
     * @return void
     */
    public static function log(string $action, array $content = [], ?string $ip = null, ?int $creatorId = null): void
    {
        event(new AdminBehaviorEvent($action, $content, $ip ?? '', $creatorId ?? 0));
    }

    /**
     * 记录操作
     */
    public static function logCreate(string $action, $behavior): void
    {
        $user = Admin::currentLoginUser();
        $logData = [
            'username'  => $user->username,
            'timestamp'  => time(),
            'module'     => '',
            'business'   => '',
            'operation'  => $behavior,
            'related_id' => 0,
            'remark'     => ''
        ];
        if ( is_array($behavior) ) {
            $logData['module']     = $behavior['module'] ?? '';
            $logData['business']   = $behavior['business'] ?? '';
            $logData['related_id'] = $behavior['related_id'] ?? '';
            $logData['operation']  = $behavior['operation'] ?? Helper::arrayToJson($behavior);
            $logData['remark']     = mb_substr($behavior['remark'] ?? '', 0, 500);
        }
        self::log($action, $logData, Helper::getClientIp(), $user->id);
    }


    /**
     * 记录登录操作
     */
    public static function logLogin(User $user): void
    {
        $content = [
            'username'   => $user->username,
            'timestamp'  => time(),
            'module'     => '账号管理',
            'business'   => '账号登录',
            'operation'  => '登录管理后台',
            'related_id' => 0,
            'remark'     => '',
        ];
        self::log('login', $content, Helper::getClientIp(), $user->id);
    }

    /**
     * 记录登出操作
     */
    public static function logLogout(User $user): void
    {
        $content = [
            'username'   => $user->username,
            'timestamp'  => time(),
            'module'     => '账号管理',
            'business'   => '注销登录',
            'operation'  => '退出管理后台',
            'related_id' => 0,
            'remark'     => '',
        ];
        self::log('logout', $content, Helper::getClientIp(), $user->id);
    }
}
